<template>
	<view class="mine">
		<!-- 	<view class="noneBox">

		</view> -->
		<u-loading-page :loading="isLoading" loading-text="加载中..."></u-loading-page>
		<image class="topBgImg" src="../../static/mine/my_bg.png" mode="widthFix"></image>
		<view class="title-content" :style="[{top:titleTop},{lineHeight:titleLineHeight}]">
			个人中心
		</view>
		<view class="topBox">
			<image :src="isLogin?userImg:userImg2" mode="widthFix" />
			<!-- <view class="bigIconBox">
			</view> -->
			<!-- <view class="weChatMsg">
				<view class="nickName">
					<text>{{userInfo.nickName}}</text>
				</view>
				<view class="phone">
					<text>{{userInfo.phone}} </text>
				</view>
			</view> -->
		</view>
		<view class="contentBox">
			<view :class="isLogin?'topTitleBox':'topTitleBox flexBox'">
				<view>Hi，用户</view>
				<view class="loginBtn" v-if="!isLogin" @click="onLoginBtnClick">
					点击登录
				</view>
				<view class="logined-box" v-else>
					<text>{{phoneTxt}}</text>
					您好
					<image @click="deleteAccount" src="../../static/mine/deleAccount.png" mode="" class="quit-image"></image>
				</view>
			</view>
			<view class="mainBox">
				<view class="main1" @click="jumpPage(1)">
					<image src="../../static/mine/myShare.png" mode=""></image>
					我的分享
				</view>
				<view class="main2" @click="jumpPage(2)">
					<image src="../../static/mine/myColloct.png" mode=""></image>
					我的收藏
				</view>
				<view class="main3" @click="jumpPage(3)">
					<image src="../../static/mine/myNotice.png" mode=""></image>
					消息管理
					<text v-if="unReadNum" class="unReadBox">{{unReadNum}}</text>
				</view>
				<!-- <view class="main4" @click="jumpPage(4)">
					<image src="../../static/mine/advice.png" mode=""></image>
					意见反馈
				</view> -->
				<view class="main5" @click="jumpPage(5)" v-if="userMsg.admin || userMsg.isAdmin">
					<image src="../../static/mine/myCode.png" mode=""></image>
					获取验证码
				</view>
			</view>
			<view class="yinsiBox" @click="onYinsiBtnClick">《隐私保护声明》</view>
		</view>
	</view>
</template>

<script>
	import {
		queryByOpenId,
		updateWechatUserAccount,
		deleteFastdfsAndFileAndUserIdCardPhoto
	} from "@/apis/userAccount.js"
	import {
		sendVerifyCode,
		deleteAccount
	} from "@/apis/index.js"
	import {
		queryMyMessageSum,
		queryWhetherUserReceiveFlag
	} from '@/apis/message.js'
	import {
		insertFeedback
	} from "@/apis/feedback.js"
	import {
		getFileByBusinessId
	} from "@/apis/fileManage.js"
	import $store from '@/store'
	import {
		baseURL
	} from "@/utils/util.js";
	import userImg from '../../static/mine/user.png'
	import userImg2 from '../../static/mine/user_1.png'
	export default {
		data() {
			return {
				isLoading: true,
				userImg,
				userImg2,
				baseURL,
				unReadNum: '', // 未读条数
				isLogin: false,
				phoneTxt: '',
				//通过微信获取的用户信息
				userInfo: {
					avatarUrl: '',
					nickName: "",
					phone: ""
				},
				//身份证正面
				fileListFront: [],
				//身份证反面
				fileListBack: [],
				show: false,
				titleObject: {
					code: "",
					title: ""
				},
				account: "",
				phone: "",
				feedback: "",
				inputValue: "",
				openId: "",
				code: "",
				userId: "",
				frontIdCardIdInFastDfs: "",
				backIdCardIdInFastDfs: "",
				frontFileId: "",
				backFileId: "",
				uNotice: "",
				userInfoDb: "",
				idCardNoPics: [],
				//是否授权
				uploadIDCardFlag: false,
				haveLogin: '',
				titleTop: '0px',
				titleLineHeight: '0px',
				userMsg:''
			}
		},
		onReady() {
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.titleTop = menuButtonInfo.top.toString() + 'px';
			this.titleLineHeight = menuButtonInfo.height.toString() + 'px';
		},
		onShow() {
			// 如果已经登录才调用接口

			if (uni.getStorageSync('token')) {
				this.isLogin = true
				this.phoneTxt = uni.getStorageSync('phone').substr(0, 3) + '****' + uni.getStorageSync('phone').substr(7,
					11)

				queryWhetherUserReceiveFlag().then(res => {
					if (res.code == '00000000') {
						// 如果消息管理里面 选了显示通知才展示未读消息数量
						if (res.data) {
							queryMyMessageSum().then(res => { // 获取未读数量
								if (res.code == '00000000') {
									this.isLoading = false
									this.unReadNum = res.data
								}
							})
						} else {
							this.unReadNum = 0
						}

					}
				})


			} else {
				this.isLogin = false
				this.phoneTxt = ''
			}


		},

		onLoad() {
			this.userMsg = uni.getStorageSync('userMsg')
		},

		methods: {
			onYinsiBtnClick() {
				uni.navigateTo({
					url: '/pages/privacy/privacy'
				})
			},
			jumpPage(val) {
				if (!uni.getStorageSync('token') && val != 4) { // 意见反馈不需要登录也能进
					uni.setStorageSync('needLogin', true)
					uni.switchTab({
						url: '/pages/index/index'
					})
					return
				}
				if(val == 5){ // 获取验证码
					sendVerifyCode().then(res=>{
						if(res.code == '00000000'){
							uni.showModal({
								showCancel:false,
								content:res.data
							})
						}
					})
					return
				}
				let pageName = ''
				val == 1 ? pageName = 'myShare' : val == 2 ? pageName = 'myCollect' : val == 3 ? pageName = 'message' :
					pageName = 'advice'
				uni.navigateTo({
					url: `/pages/${pageName}/${pageName}?type=${pageName}`
				})
			},
			onLoginBtnClick() {
				uni.setStorageSync('needLogin', true)
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			onDeleteImg(type) {
				let params = {}
				if (type == 1) {
					params = {
						userId: this.userId,
						fileId: this.idCardNoPics[0].id,
						fastDfsFileId: this.idCardNoPics[0].location
					}
					this.idCardNoPics[0].location = null
					this.fileListFront.splice(0, 1)

				} else {
					params = {
						userId: this.userId,
						fileId: this.idCardNoPics[1].id,
						fastDfsFileId: this.idCardNoPics[1].location
					}
					this.idCardNoPics[1].location = null
					this.fileListBack.splice(0, 1)

				}
				deleteFastdfsAndFileAndUserIdCardPhoto(params)
				this.$forceUpdate()
			},
			//查询身份证照片
			queryIdCardPhoto() {
				let userIdList = [this.userInfoDb.id]
				getFileByBusinessId(userIdList).then(res => {
					let fileVOList = res.data
					fileVOList.forEach(fileVO => {
						if (fileVO.businessType === 'ID_CARD_NO_FRONT') {
							this.idCardNoPics[0] = fileVO
						}
						if (fileVO.businessType === 'ID_CARD_NO_BACK') {
							this.idCardNoPics[1] = fileVO
						}

					})
					this.$forceUpdate()
				})
			},
			//根据openId查询数据库中的用户信息
			getUserInfoDb() {
				queryByOpenId({
					code: this.userInfo.openId
				}).then(res => {
					//删除缓存值
					let oldLoginName = uni.getStorageSync('userMsg').loginName
					if (oldLoginName && oldLoginName !== res.data.loginName) {
						this.idCardNoPics = []
					}
					this.userInfoDb = res.data
					if (res.data.name) {
						this.account = res.data.name
					} else {
						this.account = this.userInfo.nickName
					}
					if (res.data.phone) {
						this.phone = res.data.phone
					} else {
						this.phone = this.userInfo.phone
					}
					this.userId = res.data.id
					this.queryIdCardPhoto()
				})

			},

			//获取微信中的用户信息
			getUserInfoWx() {
				this.userInfo = uni.getStorageSync('userInfo');
				this.userInfo.phone = uni.getStorageSync('phone');
				this.userInfo.openId = uni.getStorageSync('userMsg').wechatOpenId;
				this.uploadIDCardFlag = uni.getStorageSync('uploadIDCardFlag');
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				//删除fastdfs上的图片,更新文件管理表中的数据，更新用户表中的身份中图片数据
				let params = {}
				if (event.name === 'Front') {
					params = {
						userId: this.userId,
						fileId: this.frontFileId,
						fastDfsFileId: this.frontIdCardIdInFastDfs
					}
				}
				if (event.name === 'Back' && this.backIdCardIdInFastDfs) {
					params = {
						userId: this.userId,
						fileId: this.backFileId,
						fastDfsFileId: this.backIdCardIdInFastDfs
					}
				}
				deleteFastdfsAndFileAndUserIdCardPhoto(params)
			},
			// 新增图片
			afterRead(event) {
				if (!this.haveLogin) {
					uni.showToast({
						title: '请先登录',
						icon: "none",
						duration: 1000
					});
				} else {
					if (event.file[0].size > 1024 * 1024 * 10) {
						uni.showToast({
							title: '图片大小超限制',
							icon: "none",
						});
						return
					}
					// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
					let lists = [].concat(event.file)
					let fileListLen = this[`fileList${event.name}`].length
					lists.map((item) => {
						this[`fileList${event.name}`].push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = this.uploadFilePromise(lists[i].url, event.name)
						let item = this[`fileList${event.name}`][fileListLen]
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
					}
				}

			},
			beforeRead() {
				if (!this.haveLogin) {
					uni.showToast({
						title: '请先登录',
						icon: "none",
						duration: 1000
					});
				} else {
					//如果没有授权上传身份证，需要先授权
					if (!this.uploadIDCardFlag) {
						uni.showModal({
							title: '提示',
							content: '授权小程序收集身份证信息',
							success: (res) => {
								if (res.confirm) {
									uni.setStorageSync('uploadIDCardFlag', true);
									this.uploadIDCardFlag = true
								} else if (res.cancel) {
									uni.setStorageSync('uploadIDCardFlag', false);
									this.uploadIDCardFlag = false
								}
							}
						});
					}
				}
			},

			uploadFilePromise(url, photoName) {
				let businessType = ''
				if (photoName === "Front") {
					businessType = 'ID_CARD_NO_FRONT'
				}
				if (photoName === "Back") {
					businessType = 'ID_CARD_NO_BACK'
				}
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseURL + '/user/weChat/uploadIdCardPhoto',
						filePath: url,
						name: 'file',
						header: {
							"content-type": "multipart/form-data",
							"X-App-Source": 'applet',
							"X-Access-Token": uni.getStorageSync('token')
						},
						formData: {
							"userId": this.userId,
							"businessType": businessType
						},
						success: (res) => {
							let data = JSON.parse(res.data).data
							if (photoName === 'Front') {
								this.frontIdCardIdInFastDfs = data[0].location
								this.frontFileId = data[0].id
								this.idCardNoPics[0] = data[0]
							}
							if (photoName === 'Back') {
								this.backIdCardIdInFastDfs = data[0].location
								this.backFileId = data[0].id
								this.idCardNoPics[1] = data[0]
							}

							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			//展示错误信息通知提示
			showErrorNotify(uNotice) {
				this.$refs.uNotify.show({
					top: 10,
					type: 'error',
					color: '#ffffff',
					bgColor: '#ff0000',
					message: uNotice,
					duration: 1000 * 3,
					fontSize: 20,
					safeAreaInsetTop: true
				})
			},
			//展示成功信息通知提示
			showSuccessNotify(uNotice) {
				this.$refs.uNotify.show({
					top: 10,
					type: 'error',
					color: '#ffffff',
					bgColor: '#12aa1c',
					message: uNotice,
					duration: 1000 * 3,
					fontSize: 20,
					safeAreaInsetTop: true
				})
			},
			//模态框点击确定按钮
			confirm() {
				//账号
				if (this.titleObject.code === "account") {
					//如果值为空，提示错误
					if (!this.inputValue) {
						this.showErrorNotify("账号不能为空")
					} else if (this.inputValue.length > 20) {
						this.showErrorNotify("账号长度不能大于20字符")
					} else {
						// this.account = this.inputValue
						let account = this.inputValue
						let userAccountReq = {
							id: this.userId,
							name: account
						}
						//更新数据库中登录账号名
						updateWechatUserAccount(userAccountReq).then((res) => {
							if (res.code === "00000000") {
								this.account = this.inputValue
								// this.showSuccessNotify("修改成功");
								//关闭模态框
								this.show = false;
							}
						})
						this.show = false
					}

				}

				//手机号
				if (this.titleObject.code === "phone") {

					if (!this.inputValue) {
						this.showErrorNotify("手机号不能为空")
					} else {
						if (!uni.$u.test.mobile(this.inputValue)) {
							this.showErrorNotify("手机号格式不正确")
						} else {
							let phone = this.inputValue
							let userAccountReq = {
								id: this.userId,
								phone: phone
							}
							//更新数据库中联系方式
							updateWechatUserAccount(userAccountReq).then(res => {
								if (res.code === "00000000") {
									this.phone = this.inputValue
									// this.showSuccessNotify("修改成功")
									this.show = false
								} else {
									this.inputValue = ""
									this.show = false
								}

								//关闭模态框
								this.show = false
							})
						}

					}

				}

				//意见反馈
				if (this.titleObject.code === "feedback") {
					this.feedback = this.inputValue
					if (!this.inputValue) {
						this.showErrorNotify("意见反馈不能为空")
					} else if (this.inputValue.length > 100) {
						this.showErrorNotify("意见反馈长度不能大于100字符")
					} else {
						//新增意见反馈
						let feedbackVO = {
							message: this.feedback,
							userId: this.userId,
							// contact:this.phone
						}
						insertFeedback(feedbackVO).then(res => {
							if (res.code === "00000000") {
								this.showSuccessNotify("新增成功")
							} else {
								this.inputValue = ""
							}
							this.show = false
						})
					}

				}
			},

			//模态框点击取消按钮
			cancel() {
				this.inputValue = ""
				this.show = false
			},
			//展示模态框
			modalShow(value) {
				if (!this.haveLogin) {
					uni.showToast({
						title: '请先登录',
						icon: "none",
						duration: 1000
					});
				} else {
					this.show = true
					//设置title和code和输入框的值
					if (value === "account") {
						this.titleObject = {
							code: "account",
							title: "修改账号名"
						}
						this.inputValue = this.account
					} else if (value === "feedback") {
						this.titleObject = {
							code: "feedback",
							title: "新增意见反馈"
						}
						this.inputValue = ""
					} else if (value === "phone") {
						this.titleObject = {
							code: "phone",
							title: "修改联系方式"
						}
						this.inputValue = this.phone
					} else {
						console.log("error")
					}
				}
			},

			//注销账户
			deleteAccount() {
					uni.showModal({
						title: '提示',
						content: '是否确定注销小程序账户',
						success: (res) => {
							if (res.confirm) {
								//后端清除token
								deleteAccount().then(res => {
									uni.showToast({
										title: '注销成功',
										icon: 'none',    //如果要纯文本，不要icon，将值设为'none'
										duration: 1000    //持续时间为 2秒
									})  
									//清除缓存
									uni.setStorageSync('needAuth', '');
									uni.setStorageSync('authUser', '');
									uni.setStorageSync('userInfo', '');
									uni.setStorageSync('authPhone', '');
									uni.setStorageSync('phone', '');
									uni.setStorageSync('haveLogin', '');
									uni.setStorageSync('token', '');
									uni.setStorageSync('userMsg', '');
									uni.setStorageSync('leaseInfo', '');
									uni.setStorageSync('uploadIDCardFlag', '');
									uni.setStorageSync('leaseTotal', '');
									uni.setStorageSync('unAuthApi', '');
									uni.setStorageSync('uploadIDCardFlag', '');
									//刷新我的页面数据
									this.userInfo = {
										...this.userInfo,
										phone: '',
										openId: ''
									};
									this.account = ''
									this.phone = ''
									this.uploadIDCardFlag = '';
									this.idCardNoPics = []
									this.unReadNum = 0;
									//身份证正反面清空
									this.fileListFront = []
									this.fileListBack = []
									//刷新消息页面数据
									setTimeout(()=>{
										uni.switchTab({
											url: `/pages/index/index`
										})
									},1000)
								})
							}
						}
					});
				
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import './mine.scss';
</style>